<?php

namespace app\api\controller;

use app\api\model\Coupons;
use app\api\model\OrderVip;
use app\api\model\UserBalanceLog;
use app\api\model\UserCoupons;
use app\api\model\UserGrade;
use app\api\model\Users;
use app\api\model\UserVip;
use app\api\model\UserVipCoupon;
use app\api\model\Wechat;
use app\common\controller\Api;
use think\Db;
use Yansongda\Pay\Exceptions\GatewayException;

class Vip extends Api
{
    protected $noNeedLogin = ['paymentResult'];
    protected $noNeedRight = ['*'];

    /**
     * 会员等级列表
     */
    public function index()
    {
        $vips = UserVip::getVips();
        $vips ? $this->success('请求成功', compact('vips')) : $this->error('没有数据', [], 2);
    }

    /**
     * 开通会员
     */
    public function pay($vip_id, Wechat $wechat)
    {
        $user = Users::with('userVip')->find($this->auth->getUserId());
        $vip = UserVip::find($vip_id);
        $type = $this->request->post('type');
        if (!$vip) {
            $this->error('开通会员等级不存在');
        }
        if ($user->vip >= $vip->name) {
            $this->error('您已经是当前会员了');
        }
        if ($vip->direct_upgrade <= 0) {
            $this->error('开通金额必须大于0');
        }
        $order_no = 'V'.date('YmdHis').mt_rand(100, 999);
        $data = [
            'order_no' => $order_no,
            'user_id' => $user->id,
            'user_vip_id' => $vip_id,
            'total_amount' => $vip->direct_upgrade,
            'createtime' => time(),
            'updatetime' => time()
        ];
        $order = OrderVip::create($data);
        if (!$order) {
            $this->error('创建订单失败，请联系管理员');
        }
        switch ($type) {
            //余额支付
            case 1:
                if ($user->money < $order['total_amount']) {
                    $this->error('账号余额不足');
                }
                $this->paySuccess($order, $user, $vip, 'account');
                break;
            case 2:
                try {
                    $res = $wechat->miniapp($order, $user->openid, config('wechat.notify_url'));
                } catch (\Exception $e) {
                    throw new GatewayException($e->getMessage(), $e->getCode());
                }
                $res['order_no'] = $order_no;
                isset($e) ? $this->error('支付失败，请联系管理员') : $this->success('请求成功', $res);
                break;
            default:
                $this->error('支付类型无效');
                break;
        }
    }
    /**
     * 支付回调
     */
    public function notify(Wechat $wechat)
    {
        $order_no = $this->request->post('order_no');
        if (empty($order_no)) {
            $this->error('订单号不能为空');
        }
        $order = OrderVip::getByOrderNo($order_no);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->status) {
            $this->success('支付成功', ['order_id' => $order->id]);
        }
        //查询支付结果
        $res = $wechat->find($order_no);
        if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
            if ($res['trade_state'] === 'SUCCESS') {
                $user = Users::find($order['user_id']);
                $vip = UserVip::find($order['user_vip_id']);
                $this->paySuccess($order, $user, $vip, 'wechat');
            } else {
                $this->error($res['trade_state_desc'], [], $res['trade_state']);
            }
        } else {
            $this->error('支付失败，请联系管理员');
        }

    }

    /**
     * 支付结果通知
     */
    public function paymentResult(Wechat $wechat)
    {
        $res = $wechat->verify();
        if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
            $order = OrderVip::getByOrderNo($res['out_trade_no']);
            if ($order && $order->status == 0) {
                $user = Users::find($order['user_id']);
                $vip = UserVip::find($order['user_vip_id']);
                $this->paySuccess($order, $user, $vip, 'wechat');
            }
        }
        $wechat->wechatPay()->success()->send();
    }

    private function paySuccess($order, $user, $vip, $type)
    {
        Db::startTrans();
        try {
            //更新订单
            $order->type = $type;
            $order->status = 1;
            $order->save();
            //记录等级变化
            UserGrade::add($user->id, $user->vip, $vip->name, 1);
            //更新会员
            if ($type == 'account') {
                $user->money = $user->money - $order->total_amount > 0 ?  $user->money - $order->total_amount : 0;
                //记录余额变化
                UserBalanceLog::add($user->id, -$order->total_amount, $order->order_no, 5);
            }
            if ($type == "wechat") {
                $user->money += $order->total_amount;
                //记录余额变化
                UserBalanceLog::add($user->id, $order->total_amount, $order->order_no, 5);
            }
            $user->is_vip = 'yes';
            $user->vip = $vip->name;
            $user->expense_money += $order->total_amount;
            $user->ontime = time();
            $user->save();
            //赠送优惠券
            $user_vip_coupon = UserVipCoupon::getByUserVip($vip->id);
            if ($user_vip_coupon) {
                foreach ($user_vip_coupon as $val) {
                    $coupon = Coupons::find($val['coupon_id']);
                    if ($coupon) {
                        for ($i = 0; $i < $val['num']; $i++) {
                            UserCoupons::createUserCoupon($order->user_id, $coupon, true);
                        }
                    }
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        isset($e) ? $this->error('支付失败，请联系管理员') : $this->success('支付成功', ['order_id' => $order->id]);
    }

}
